package de.szut.traineeslife.taks;

import java.io.IOException;
import java.util.ArrayList;

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import de.szut.traineeslife.utils.DialogListener;
import de.szut.traineeslife.utils.DriveHelper;
import de.szut.traineeslife.utils.FileHelper;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

public class PrepareDriveTask extends AsyncTask<Void, Void, Void> {
	
	private ProgressDialog dialog;
	private Context mContext;
	private Drive mService;
	private final Uri mFileUri;
	private FileHelper mFileHelper;
	private String folderID;
	private DriveHelper mDriveHelper;
	private boolean folderSucces = true;
	private DialogListener mDialogListener;
	private File driveFile = null;
	
	public PrepareDriveTask(Context context, Drive service,DriveHelper driveHelper,Uri fileUri, FileHelper fileHelper,DialogListener dialogListener) {
		mContext = context;
		mService = service;
		mDriveHelper = driveHelper;
		mDialogListener = dialogListener;
		mFileUri = fileUri;
		mFileHelper = fileHelper;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			ArrayList<File> driveList = mDriveHelper.getDrivesFolderList(mService);
			folderID = mDriveHelper.checkForAppFolder(driveList);
			if (folderID == "") {
				folderSucces = mDriveHelper.createAppFolder(mService, folderID);
			}
			Thread.sleep(5000);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		try {
			if(folderSucces == true){
				driveFile = mDriveHelper.saveFileToDrive(mFileUri, mService, mFileHelper,"TraineesLife_Vorlage");
			}
			Thread.sleep(2000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		if (folderSucces == false  && driveFile == null) {
			Toast.makeText(mContext, "Beim vorbereiten von Drive ist ein Fehler aufgetreten", Toast.LENGTH_LONG).show();
		}else{
			mDialogListener.finishAuthentication();
		}
		if (dialog != null) {
			dialog.dismiss();
		}
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = new ProgressDialog(this.mContext);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setMessage("Drive wird vorbereitet....");
		dialog.setCancelable(false);
		dialog.show();
	}

}
